package com.yantong.service.impl;

import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.BalanceExcelVo;
import com.yantong.service.BalanceService;
import com.yantong.service.ConfigService;
import com.yantong.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author kanghaixin
 * @date 2018/9/16.9:24
 */
@Service
public class BalanceServiceImpl implements BalanceService {

    private static final Logger logger = LoggerFactory.getLogger(BalanceServiceImpl.class);
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private BalanceLogMapper balanceLogMapper;
    @Autowired
    private WithdrawalsMapper withdrawalsMapper;
    @Autowired
    private CentreAmountMapper centreAmountMapper;
    @Autowired
    private AmountLogMapper amountLogMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private ShipcardRecordMapper shipcardRecordMapper;
    @Autowired
    private ConfigService configService;

    @Override
    public PageUtils<Balance> listBalances(Integer role, Date start, Date end, String queryItem,
                                           Long centreId, Long teamId, int offset, int limit) {
        PageUtils<Balance> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(4);
        if (role != null) {
            params.put("role", role);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        int total = memberMapper.countBalanceByParams(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(memberMapper.listBalancesByParams(params, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    @Override
    public List<Balance> listBalances(Integer role, Date start, Date end, String queryItem, Long centreId) {
        Map<String, Object> params = new HashMap<>(4);
        if (role != null) {
            params.put("role", role);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        params.put("minMoney", 0);
        return memberMapper.listBalancesByParams(params);
    }

    @Override
    public Balance getBalanceDetail(Long mid) {
        if (mid == null) {
            return null;
        }
        return memberMapper.getBalanceDetail(mid);
    }

    @Override
    public double getBalanceSum(Integer role, Date start, Date end, String queryItem, Long centreId) {
        Map<String, Object> params = new HashMap<>(4);
        if (role != null) {
            params.put("role", role);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        return memberMapper.getBalanceSum(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recharge(Long mid, Double money, Integer style, String title, String remark) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        //扣除商户余额
//        int r = centreAmountMapper.deductAmount(balance.getCentreId(), BigDecimal.valueOf(money));
//        if (r < 1) {
//            throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
//        }
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(0);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(money));
        log.setAfteramount(balance.getBalance().add(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int tfbRecharge(Long mid, Double money, Integer style, String title, String remark) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
//        //扣除商户余额
//        int r = centreAmountMapper.deductAmount(balance.getCentreId(), BigDecimal.valueOf(money));
//        if (r < 1) {
//            throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
//        }
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(0);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(money));
        log.setAfteramount(balance.getBalance().add(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deduct(Long mid, Double money, Integer style, String title, String remark, Long shipcardId, String shipcardName) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        if (money > balance.getBalance().doubleValue()) {
            throw new BDException(BusinessCode.DEDUCT_OVER_BALANCE);
        }

        /*int r = centreAmountMapper.changeAmount(new CentreAmount(balance.getCentreId(), BigDecimal.valueOf(money)));
        if (r <1) {
            return 0;
        }*/
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(1);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(-money));
        log.setAfteramount(balance.getBalance().subtract(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        if (shipcardId != null) {
            log.setShipcardId(shipcardId);
        }
        if (StringUtils.isNotEmpty(shipcardName)) {
            log.setShipcardName(shipcardName);
        }
        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, -money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deductOfShipcard(Long mid, Double money, Integer style, String title, String remark, Long shipcardRecordId) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        ShipcardRecord shipcardRecord = shipcardRecordMapper.selectByPrimaryKey(shipcardRecordId);
        if (shipcardRecord == null) {
            logger.info("not found shipcardRecord by id:{}", shipcardRecordId);
            return 0;
        }
        if (money > shipcardRecord.getPrice().doubleValue()) {
            throw new BDException(BusinessCode.DEDUCT_OVER_BALANCE);
        }
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(1);
        log.setStyle(style);
        log.setBeforeamount(shipcardRecord.getPrice());
        log.setMoney(new BigDecimal(-money));
        log.setAfteramount(shipcardRecord.getPrice().subtract(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        log.setShipcardRecordId(shipcardRecordId);
        balanceLogMapper.insertSelective(log);
        return shipcardRecordMapper.rechargeBalance(shipcardRecordId, -money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int rechargeOfShipcard(Long mid, Double money, Integer style, String title, String remark, Long shipcardRecordId) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        ShipcardRecord shipcardRecord = shipcardRecordMapper.selectByPrimaryKey(shipcardRecordId);
        if (shipcardRecord == null) {
            logger.info("not found shipcardRecord by id:{}", shipcardRecordId);
            return 0;
        }
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(0);
        log.setStyle(style);
        log.setBeforeamount(shipcardRecord.getPrice());
        log.setMoney(new BigDecimal(money));
        log.setAfteramount(shipcardRecord.getPrice().add(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        log.setShipcardRecordId(shipcardRecordId);
        balanceLogMapper.insertSelective(log);
        return shipcardRecordMapper.rechargeBalance(shipcardRecordId, money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cash(Long mid, Double money, String remark, String isgys, String bankcard) {
        if (mid == null || money == null || money < 1) {
            return 0;
        }

        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        if (money > balance.getBalance().doubleValue()) {
            throw new BDException(BusinessCode.CASH_OVER_BALANCE);
        }
        Member member = memberMapper.selectByPrimaryKey(mid);

        TradeConfig tradeConfig = configService.getTradeConfig(member.getCentreId());
        if (null != tradeConfig && money < tradeConfig.getCashLimit()) {
            throw new BDException("最小提现金额为" + tradeConfig.getCashLimit() + "元");
        }

        Map<String, Object> params = new HashMap<String, Object>();
        if (mid != null) {
            params.put("mid", mid);
        }
        if (bankcard != null) {
            params.put("cardNo", bankcard);
        }
        List<MemberCard> cardList = cardMapper.getListByParams(params);
        String realname = member.getRealname();
        String bankname = StringConstans.STR_EMPTY;
        if (cardList.size() == 1) {
            realname = cardList.get(0).getUsername();
            bankname = cardList.get(0).getBbName();
        }
        if (org.springframework.util.StringUtils.isEmpty(realname)) {
            throw new BDException(BusinessCode.TFB_DF_FAIL2);
        }
        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(realname.equals("") ? member.getRealname() : realname);
        log.setTitle(RechargeType.BEHIND_CASH.getType());
        log.setStatus(1);

        if (!org.springframework.util.StringUtils.isEmpty(isgys) && isgys.equals("1")) {
            log.setStyle(8);
            //流水类型:供应商提现申请
            log.setFlowtype("18");
            log.setSource(2);//来源为供应商用户
        } else {
            log.setStyle(2);
            //判断该笔提现是否是门店  流水类型:门店提现申请/流水类型:用户提现申请
            log.setFlowtype(balance.getIsteam() == 3 ? "17" : "16");
            log.setSource(balance.getIsteam() == 3 ? 1 : 0);//会员用户/门店余额变更
        }
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(-money));
        log.setAfteramount(balance.getBalance().subtract(new BigDecimal(money)));
        log.setRemark("后台提现申请");
        log.setCentreId(balance.getCentreId());

        balanceLogMapper.insertSelective(log);

        /**生成提现申请记录**/
        Withdrawals withdrawals = new Withdrawals();
        withdrawals.setApplyno(CommonUtils.getSn("WTX"));
        withdrawals.setMid(mid);
        if (!org.springframework.util.StringUtils.isEmpty(isgys) && isgys.equals("1")) {
            withdrawals.setRole(1);//供应商
        } else {
            withdrawals.setRole(balance.getIsteam() == 3 ? 3 : 0);
        }
        withdrawals.setBankcard(bankcard);
        withdrawals.setRealname(realname.equals("") ? member.getRealname() : realname);
        withdrawals.setMoney(new BigDecimal(money));
        withdrawals.setDaMoney(withdrawals.getMoney());
        withdrawals.setStatus(CashStatus.APPLY.getCode());
        withdrawals.setCentreId(balance.getCentreId());
        withdrawals.setBankname(bankname);
        //查询供应商
        withdrawalsMapper.insertSelective(withdrawals);

        if (!org.springframework.util.StringUtils.isEmpty(isgys) && isgys.equals("1")) {
            return 0;
        } else {
            return memberMapper.rechargeBalance(mid, -money);
        }

    }

    @Override
    public PageUtils<BalanceLog> listBalanceLogs(Long centreId, Long teamId, Date start, Date end, Integer style, String queryItem, String source, String flowtype, int offset, int limit) {
        PageUtils<BalanceLog> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(8);
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (style != null) {
            params.put("style", style);
        }
        if (StringUtils.isNotEmpty(flowtype)) {
            params.put("flowtype", flowtype);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (StringUtils.isNotEmpty(source)) {
            params.put("source", source);
            //如果查询记录来源为供应商，则判断centreid是否为空，为空则查询平台供应商，否则查询站点自己供应商
            if (centreId == null && source.equals("2")) params.put("suppliertype", 0);
            else if (centreId != null && source.equals("2")) params.put("suppliertype", 1);

        }
        int total = balanceLogMapper.countByParams(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            List<BalanceLog> logs = balanceLogMapper.listByParams(params, new RowBounds(offset, limit));
            for (BalanceLog log : logs) {
                log.setStyleName(BalanceLogStyle.get(log.getStyle()));
            }
            pageUtils.setRows(logs);
        }
        return pageUtils;
    }

    @Override
    public List<BalanceLog> listBalanceLogs(Long centreId, Long teamId, Date start, Date end, Integer style, String queryItem, String source, String flowtype) {
        Map<String, Object> params = new HashMap<>(8);
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (style != null) {
            params.put("style", style);
        }
        if (StringUtils.isNotEmpty(flowtype)) {
            params.put("flowtype", flowtype);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (StringUtils.isNotEmpty(source)) {
            params.put("source", source);
            //如果查询记录来源为供应商，则判断centreid是否为空，为空则查询平台供应商，否则查询站点自己供应商
            if (centreId == null && source.equals("2")) params.put("suppliertype", 0);
            else if (centreId != null && source.equals("2")) params.put("suppliertype", 1);

        }
        return balanceLogMapper.listByParams(params);
    }

    @Override
    public PageUtils<BalanceLog> listBalanceLogs(BalanceLog balanceLog, int offset, int limit) {
        PageUtils<BalanceLog> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(8);
        if (balanceLog.getMid() != null) {
            params.put("mid", balanceLog.getMid());
        }
        if (balanceLog.getStart() != null) {
            params.put("start", balanceLog.getStart());
        }
        if (balanceLog.getEnd() != null) {
            params.put("end", balanceLog.getEnd());
        }
        if (balanceLog.getStyle() != null) {
            params.put("style", balanceLog.getStyle());
        }
        if (balanceLog.getShipcardRecordId() != null) {
            params.put("shipcardRecordId", balanceLog.getShipcardRecordId());
        }
        int total = balanceLogMapper.countByParams(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            List<BalanceLog> logs = balanceLogMapper.listByParams(params, new RowBounds(offset, limit));
            for (BalanceLog log : logs) {
                log.setStyleName(BalanceLogStyle.get(log.getStyle()));
            }
            pageUtils.setRows(logs);
        }
        return pageUtils;
    }

    @Override
    public PageUtils<BalanceLog> listBalanceLogsBefore(BalanceLog balanceLog, int offset, int limit) {
        PageUtils<BalanceLog> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(8);
        if (balanceLog.getMid() != null) {
            params.put("mid", balanceLog.getMid());
        }
        if (balanceLog.getStart() != null) {
            params.put("start", balanceLog.getStart());
        }
        if (balanceLog.getEnd() != null) {
            params.put("end", balanceLog.getEnd());
        }
        if (balanceLog.getStyle() != null) {
            params.put("style", balanceLog.getStyle());
        }
        if (balanceLog.getShipcardRecordId() != null) {
            params.put("shipcardRecordId", balanceLog.getShipcardRecordId());
        }
        int total = balanceLogMapper.countByParams(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            List<BalanceLog> logs = balanceLogMapper.listByParams(params, new RowBounds(offset, limit));
            for (BalanceLog log : logs) {
                log.setStyleName(BalanceLogStyle.get(log.getStyle()));
            }
            pageUtils.setRows(logs);
        }
        return pageUtils;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRecharge(List<BalanceExcelVo> list) {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        for (BalanceExcelVo bev : list) {
            if (bev == null || bev.getAmount() == null || bev.getMid() == null) {
                continue;
            }
            Long mid = bev.getMid();
            BigDecimal amount = bev.getAmount();

            Balance balance = memberMapper.getBalanceDetail(bev.getMid());
            if (balance == null) {
                logger.info("not found member by mid:{}", bev.getMid());
                continue;
            }

            //生成商户扣除记录
            AmountLog al = new AmountLog();
            al.setCentreId(balance.getCentreId());
            al.setMoney(BigDecimal.ZERO.subtract(amount));
            al.setRemark(mid + "用户充值,扣除商户余额(批量充值)");
            CentreAmount centreAmount = centreAmountMapper.getByKey(balance.getCentreId());
            al.setBeforeamount(centreAmount.getAmount());
            al.setAfteramount(centreAmount.getAmount().subtract(amount));

            //扣除商户余额
            int r = centreAmountMapper.deductAmount(balance.getCentreId(), amount);
            if (r < 1) {
                logger.info("商户账户余额不足，充值失败，会员ID：{}, 金额:{}", mid, amount);
                continue;
            }
            amountLogMapper.saveAmountLog(al);

            BalanceLog log = new BalanceLog();
            log.setMid(mid);
            log.setMobile(balance.getMobile());
            log.setRealname(balance.getRealname());
            log.setTitle(RechargeType.BEHIND_RECHARGE.getType());
            log.setStatus(0);
            log.setStyle(BalanceLogStyle.RECHARGE.getCode());
            log.setBeforeamount(balance.getBalance());
            log.setMoney(amount);
            log.setAfteramount(balance.getBalance().add(amount));
            log.setCentreId(balance.getCentreId());
            if (balance.getIsteam() == 3) {
                log.setFlowtype("8");//流水类型:门店充值
            } else {
                log.setFlowtype("3");//流水类型:用户充值
            }
            String remark = "批量充值";
            if (StringUtils.isNotEmpty(bev.getTname())) {
                remark = remark.concat(bev.getTname());
            }
            if (StringUtils.isNotEmpty(bev.getRemark())) {
                remark = remark.concat(bev.getRemark());
            }
            log.setRemark(remark);
            log.setSource(0);//会员用户余额变更
            balanceLogMapper.insertSelective(log);

            memberMapper.rechargeBalance(mid, amount.doubleValue());
        }
        return 1;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int balanceRecharge(Long mid, Double money, Integer style, String title, String remark) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //生成商户扣除记录
        AmountLog al = new AmountLog();
        al.setCentreId(balance.getCentreId());
        al.setMoney(BigDecimal.valueOf(-money));
        al.setFlowType(7);//站点给用户或门店充值
        al.setRemark(mid + ",用户充值,扣除商户余额".concat(",IP:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
        CentreAmount centreAmount = centreAmountMapper.getByKey(balance.getCentreId());
        al.setBeforeamount(centreAmount.getAmount());
        al.setAfteramount(centreAmount.getAmount().subtract(BigDecimal.valueOf(money)));

        //扣除商户余额
        int r = centreAmountMapper.deductAmount(balance.getCentreId(), BigDecimal.valueOf(money));
        if (r < 1) {
            throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
        }
        amountLogMapper.saveAmountLog(al);

        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(0);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(money));
        log.setAfteramount(balance.getBalance().add(new BigDecimal(money)));
        log.setRemark(remark.concat(",IP:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int balanceDeduct(Long mid, Double money, Integer style, String title, String remark) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }
        if (money > balance.getBalance().doubleValue()) {
            throw new BDException(BusinessCode.DEDUCT_OVER_BALANCE);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        //生成商户充值记录
        AmountLog al = new AmountLog();
        al.setCentreId(balance.getCentreId());
        al.setMoney(BigDecimal.valueOf(money));
        al.setFlowType(8);
        al.setRemark(mid + ",用户扣除,充值商户余额".concat(",IP:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
        CentreAmount centreAmount = centreAmountMapper.getByKey(balance.getCentreId());
        al.setBeforeamount(centreAmount.getAmount());
        al.setAfteramount(centreAmount.getAmount().add(BigDecimal.valueOf(money)));

        int r = centreAmountMapper.changeAmount(new CentreAmount(balance.getCentreId(), BigDecimal.valueOf(money)));
        if (r < 1) {
            return 0;
        }
        amountLogMapper.saveAmountLog(al);

        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(1);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(-money));
        log.setAfteramount(balance.getBalance().subtract(new BigDecimal(money)));
        log.setRemark(remark.concat(",IP:").concat(IPUtils.getIpAddr(request)).concat(",操作人:").concat(ShiroUtils.getUser().getNickname()));
        log.setCentreId(balance.getCentreId());
        log.setSource(0);//会员用户余额变更
        if (balance.getIsteam() == 3) {
            log.setFlowtype("9");//流水类型:门店扣款
        } else {
            log.setFlowtype("4");//流水类型:用户扣款
        }

        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, -money);
    }


    @Override
    public int takeMoney(Long mid, Double money, Integer style, String title, String remark, String workson, Long orderCentreId) {
        if (mid == null || money == null) {
            return 0;
        }
        Balance balance = memberMapper.getBalanceDetail(mid);
        if (balance == null) {
            logger.info("not found member by mid:{}", mid);
            return 0;
        }

        //生成商户扣除记录
        AmountLog al = new AmountLog();
        al.setCentreId(orderCentreId);
        al.setMoney(BigDecimal.valueOf(-money));
        al.setFlowType(2);//站点门店佣金发放
        al.setRemark("售后工单" + workson + ",商户扣款,门店:" + mid);
        CentreAmount centreAmount = centreAmountMapper.getByKey(orderCentreId);
        al.setBeforeamount(centreAmount.getAmount());
        al.setAfteramount(centreAmount.getAmount().subtract(BigDecimal.valueOf(money)));

        //扣除商户余额
//        int r = centreAmountMapper.deductAmount(orderCentreId, BigDecimal.valueOf(money));
//        if (r < 1) {
//            throw new BDException(BusinessCode.CENTER_AMOUNT_NO_BALANCE);
//        }
        amountLogMapper.saveAmountLog(al);

        BalanceLog log = new BalanceLog();
        log.setMid(mid);
        log.setMobile(balance.getMobile());
        log.setRealname(balance.getRealname());
        log.setTitle(title);
        log.setStatus(0);
        log.setStyle(style);
        log.setBeforeamount(balance.getBalance());
        log.setMoney(new BigDecimal(money));
        log.setAfteramount(balance.getBalance().add(new BigDecimal(money)));
        log.setRemark(remark);
        log.setCentreId(orderCentreId);
        log.setFlowtype("10");//流水类型:门店退款
        log.setSource(0);//会员用户余额变更
        balanceLogMapper.insertSelective(log);
        return memberMapper.rechargeBalance(mid, money);
    }

    @Override
    public PageUtils<BalanceCWLog> listSupplyCwBalanceLogs(Long centreId, Date start, Date end, Integer style,
                                                           String queryItem, String realname, String mobile, String nickname, String flowtype, int offset, int limit) {
        PageUtils<BalanceCWLog> pageUtils = new PageUtils<>();
        Map<String, Object> params = new HashMap<>(8);
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (style != null) {
            params.put("style", style);
        }
        if (StringUtils.isNotEmpty(flowtype)) {
            params.put("flowtype", flowtype);
        }

        if (StringUtils.isNotEmpty(realname)) {
            params.put("realname", realname);
        }
        if (StringUtils.isNotEmpty(mobile)) {
            params.put("mobile", mobile);
        }
        if (StringUtils.isNotEmpty(nickname)) {
            params.put("nickname", nickname);
        }
        int total = balanceLogMapper.countSupplyCwBalanceLogs(params);
        if (total > 0) {
            pageUtils.setTotal(total);
            List<BalanceCWLog> logs = balanceLogMapper.listSupplyCwBalanceLogs(params, new RowBounds(offset, limit));
            pageUtils.setRows(logs);
        }
        return pageUtils;
    }

    @Override
    public List<BalanceCWLog> listAllBalanceLogs(Long centreId, Date start, Date end, Integer style, String queryItem,
                                                 String realname, String mobile, String nickname, String flowtype) {
        Map<String, Object> params = new HashMap<>(8);
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (style != null) {
            params.put("style", style);
        }
        if (StringUtils.isNotEmpty(flowtype)) {
            params.put("flowtype", flowtype);
        }

        if (StringUtils.isNotEmpty(realname)) {
            params.put("realname", realname);
        }
        if (StringUtils.isNotEmpty(mobile)) {
            params.put("mobile", mobile);
        }
        if (StringUtils.isNotEmpty(nickname)) {
            params.put("nickname", nickname);
        }
        return balanceLogMapper.listAllBalanceLogs(params);

    }

    /**
     * 得到账户供应商流水
     *
     * @param mid
     * @param offset
     * @param limit
     * @return
     */
    public PageUtils<BalanceLog> getsupllyBalanceLog(Long mid, Long flowtype, int offset, int limit) {
        PageUtils<BalanceLog> pageUtils = new PageUtils<>();
        if (mid == null) {
            logger.info("not found member by mid:{}", mid);
            return null;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        if (mid != null) {
            params.put("mid", mid);
        }
        if (flowtype != null) {
            params.put("flowtype", flowtype);
        }
        params.put("source", 2);
        List<BalanceLog> list = balanceLogMapper.listByParams(params, new RowBounds(offset, limit));
        if (list.size() > 0) {
            pageUtils.setTotal(balanceLogMapper.countByParams(params));
            pageUtils.setRows(list);
        }
        return pageUtils;
    }


    /**
     * 总金额
     *
     * @param centreId
     * @param start
     * @param end
     * @param style
     * @param queryItem
     * @return
     */
    public String sumByMoney(Long centreId, Long teamId, Date start, Date end, Integer style, String queryItem, String source, String flowtype) {
        Map<String, Object> params = new HashMap<>(8);
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (style != null) {
            params.put("style", style);
        }
        if (StringUtils.isNotEmpty(flowtype)) {
            params.put("flowtype", flowtype);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (StringUtils.isNotEmpty(source)) {
            params.put("source", source);
            //如果查询记录来源为供应商，则判断centreid是否为空，为空则查询平台供应商，否则查询站点自己供应商
            if (centreId == null && source.equals("2")) params.put("suppliertype", 0);
            else if (centreId != null && source.equals("2")) params.put("suppliertype", 1);

        }
        return balanceLogMapper.sumByMoney(params);

    }

    ;
}
